package cn.zhao.service;


import cn.zhao.entity.JwtUserDto;
import cn.zhao.dao.UserMapper;
import cn.zhao.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 原本在内存中查找用户信息
 * 重写这个接口改为从数据库查询
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库查询user
        User user = userMapper.findByUserName(username);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("用户名密码错误！");
        }

        //TODO: 改为数据库查询权限信息
        List<String> permission = new ArrayList<>(Arrays.asList("test","admin"));
        return new JwtUserDto(user,permission);
    }
}
